import Vue from 'vue';
import axios from 'axios';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

const service = axios.create({
	baseURL: "https://www.aaxing14.top:8101/user",
	timeout: 6000,
})

// 请求拦截
service.interceptors.request.use(config => {
    console.log("// 请求拦截:", config.url);
    if (config.url.indexOf("login") < 0) {
        config.headers['token'] = uni.getStorageSync('token');
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截
service.interceptors.response.use(
    response => {
        // 正常响应的处理逻辑
        console.log("响应拦截器:", response);
        if (response.status === 200) {
            if (response.data && response.data.code === 100) {
                const token = response.headers?.['token'];
                if (token) {
                    uni.setStorageSync('token', token);
                }
            }
            return response.data; // 返回处理后的数据
        } else {
            return Promise.reject(response);
        }
    },
    error => {
        console.error("响应拦截器错误:", error);
        // 检查是否为 401 错误
        if (error.response && error.response.status === 401) {
            console.warn("认证失败，跳转到登录页面");
            uni.showToast({
                title: "登录信息已失效，请重新登录",
                icon: "none",
                duration: 2000
            });
            // 跳转到登录页面
            // uni.redirectTo({
            //     url: '/pages/login/login' // 登录页面路径，根据项目修改
            // });
        }
        return Promise.reject(error); // 将错误传递给调用方
    }
);


// 自定义适配器
axios.defaults.adapter = function(config) {
    return new Promise((resolve, reject) => {
        let settle = require('axios/lib/core/settle');
        let buildURL = require('axios/lib/helpers/buildURL');
        let buildFullPath = require('axios/lib/core/buildFullPath');
        let fullurl = buildFullPath(config.baseURL, config.url);
        uni.request({
            method: config.method.toUpperCase(),
            url: buildURL(fullurl, config.params, config.paramsSerializer),
            header: config.headers,
            data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
            dataType: config.dataType,
            responseType: config.responseType,
            sslVerify: config.sslVerify,
            complete: function complete(response) {
                response = {
                    data: response.data,
                    status: response.statusCode,
                    errMsg: response.errMsg,
                    headers: response.header,
                    config: config,
                };
                settle(resolve, reject, response);
            },
        });
    });
};

export default service;
